﻿@using Volo.Abp.Localization
@using System.Globalization
@using System.Collections.Immutable
@inject ILanguageProvider LanguageProvider
@inject IJSRuntime JsRuntime
@if (_otherLanguages != null && _otherLanguages.Any())
{
    <BarDropdown>
        <BarDropdownToggle>
            @_currentLanguage.DisplayName
        </BarDropdownToggle>
        <BarDropdownMenu RightAligned="true">
            @foreach (var language in _otherLanguages)
            {
                <BarDropdownItem Clicked="() => ChangeLanguageAsync(language)">@language.DisplayName</BarDropdownItem>
            }
        </BarDropdownMenu>
    </BarDropdown>
}
@code {
    private IReadOnlyList<LanguageInfo> _otherLanguages;
    private LanguageInfo _currentLanguage;

    protected async override Task OnInitializedAsync()
    {
        var selectedLanguageName = await JsRuntime.InvokeAsync<string>(
            "localStorage.getItem",
            "Abp.SelectedLanguage"
            );

        _otherLanguages = await LanguageProvider.GetLanguagesAsync();

        if (!_otherLanguages.Any())
        {
            return;
        }

        if (!selectedLanguageName.IsNullOrWhiteSpace())
        {
            _currentLanguage = _otherLanguages.FirstOrDefault(l => l.UiCultureName == selectedLanguageName);
        }

        if (_currentLanguage == null)
        {
            _currentLanguage = _otherLanguages.FirstOrDefault(l => l.UiCultureName == CultureInfo.CurrentUICulture.Name);
        }

        if (_currentLanguage == null)
        {
            _currentLanguage = _otherLanguages.FirstOrDefault();
        }

        _otherLanguages = _otherLanguages.Where(l => l != _currentLanguage).ToImmutableList();
    }

    private async Task ChangeLanguageAsync(LanguageInfo language)
    {
        await JsRuntime.InvokeVoidAsync(
            "localStorage.setItem",
            "Abp.SelectedLanguage", language.UiCultureName
            );

        await JsRuntime.InvokeVoidAsync("location.reload");
    }
}
